package com.netpace.iem.ahmed.utilities;

import java.io.Closeable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.log4j.Logger;

public class SQLDataSource implements Closeable {
	
	private static final String USERNAME = "root";
	private static final String PASSWORD = "";
	private static final String MYSQL_CONNECTION_STRING = 
			"jdbc:mysql://localhost/iem";
	
	private Connection connect;
	private Statement statement;
	private ResultSet resultSet;
	private Logger log = Logger.getLogger(SQLDataSource.class);

	public SQLDataSource() throws Exception  {
		connectDatabase();
	}
	
	public ResultSet executeQuery(String query) throws Exception {
		log.info(query);
		statement = connect.createStatement();
		return  statement.executeQuery(query);		
	}
	
	public void executeNonQuery(String query) throws Exception {
		log.info(query);
		statement = connect.createStatement();
		statement.executeUpdate(query);
	}

	public void connectDatabase() throws Exception {
		if(connect != null)
			return;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connect = DriverManager
					.getConnection(MYSQL_CONNECTION_STRING, USERNAME, PASSWORD);
		} catch (Exception e) {
			throw e;
		} 

	}

	public void close() {
		try {
			if (resultSet != null) {
				resultSet.close();
			}

			if (statement != null) {
				statement.close();
			}

			if (connect != null) {
				connect.close();
			}
		} catch (Exception e) {

		}
	}
}
